package com.wenhai.spring.bean.definition;

import com.wenhai.xiaomage.spring.ioc.overview.dependency.domain.User;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionReaderUtils;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * @Author:wenhai
 * @Description: @Bean,@Component,@Import
 * @Date:2020/3/24
 */
@Import(AnnotationBeanDefinitionDemo.Config.class)
public class AnnotationBeanDefinitionDemo {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext cxt = new AnnotationConfigApplicationContext();
        cxt.register(AnnotationBeanDefinitionDemo.class);
        cxt.refresh();
        registerUserBeanDefinition(cxt, "bean-name");
        registerUserBeanDefinition(cxt);
        System.out.println("Config 类型的所有Bean：" + cxt.getBeansOfType(Config.class));
        System.out.println("User 类型的所有Bean：" + cxt.getBeansOfType(User.class));

        cxt.close();
    }

    /**
     * 通过命名/非命名方式注册Bean
     *
     * @param beanDefinitionRegistry bean definition registry
     * @param beanName               the register bean name
     */
    public static void registerUserBeanDefinition(BeanDefinitionRegistry beanDefinitionRegistry, String beanName) {
        BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(User.class);
        beanDefinitionBuilder.addPropertyValue("id", System.currentTimeMillis()).addPropertyValue("username", "注册register");
        if (StringUtils.hasText(beanName)) {
            beanDefinitionRegistry.registerBeanDefinition(beanName, beanDefinitionBuilder.getBeanDefinition());
        } else {
            // 非命名的方式
            BeanDefinitionReaderUtils.registerWithGeneratedName(beanDefinitionBuilder.getBeanDefinition(), beanDefinitionRegistry);
        }
    }


    private static void registerUserBeanDefinition(BeanDefinitionRegistry beanDefinitionRegistry) {
        registerUserBeanDefinition(beanDefinitionRegistry, "");
    }

    @Component
    static class Config {

        @Bean(name = "user,wenhai-user")
        public User user() {
            User user = new User(10L);
            user.setUsername("configBean");
            return user;
        }
    }

}
